# -*- coding: utf-8 -*-

import sys
import os
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from datetime import datetime
import SendMsg
import traceback
from PrintLogger import setup_print_log
from SettingLoader import Setting
# print 重定向
setup_print_log()

# 配置设置
# ----------------------------------------------

global global_user_name
global global_passward
global global_href
global global_msg_receive_phone_number
global binary_location
global executable_path


def load_global_setting():
    '''
    加载全局配置
    '''
    global global_user_name
    global global_passward
    global global_href
    global global_msg_receive_phone_number
    global binary_location
    global executable_path
    global_setting = Setting().setting
    global_user_name = global_setting['global_user_name']
    global_passward = global_setting['global_passward']
    global_href = global_setting['single_run_url']
    global_msg_receive_phone_number = global_setting['global_msg_receive_phone_number']
    binary_location = global_setting['binary_location']
    executable_path = global_setting['executable_path']



#######################################################################
def start_browser(window_size=(375, 980)):
    '''
    启动浏览器，返回browser
    '''
    try:
        chrome_options = Options()
        chrome_driver = chrome_options.binary_location
        browser = webdriver.Chrome()
    except Exception as e:
        # 无法自动获取，就需要手动设置
        chrome_options = Options()
        print('=============================================================')
        print(f'需要手动设置谷歌浏览器的执行文件位置和谷歌驱动位置')
        print('=============================================================')
        chrome_options.binary_location = binary_location
        browser = webdriver.Chrome(executable_path=executable_path, options=chrome_options)
    # 把屏幕设置为和手机相当大小
    browser.set_window_size(window_size[0], window_size[1])
    return browser


def browser_login(browser, user, passward):
    '''
    登陆
    param:
     user 用户名
     passward 密码
    '''
    browser.get("https://fmall.gree.com/mobile/index.html#/login")
    WebDriverWait(browser, 10).until(
        lambda browser: browser.find_element_by_xpath('//*[@id="app"]/div[1]/div/div[1]/div[2]/div[2]')).click()
    WebDriverWait(browser, 10).until(
        lambda browser: browser.find_element_by_xpath(
            '//*[@id="app"]/div[1]/div/div[1]/div[3]/div/div[1]/div/input')).send_keys(user)
    WebDriverWait(browser, 10).until(
        lambda browser: browser.find_element_by_xpath(
            '//*[@id="app"]/div[1]/div/div[1]/div[3]/div/div[2]/div/input')).send_keys(passward)
    WebDriverWait(browser, 10).until(
        lambda browser: browser.find_element_by_xpath('//*[@id="app"]/div[1]/div/div[1]/div[3]/div/p[1]')).click()


def browser_close_popup(browser):
    '''
    关闭弹窗
    '''
    try:
        btn_div = WebDriverWait(browser, 10).until(
            lambda browser: browser.find_element_by_css_selector(
                "[class='close_Popup']"))
        browser.execute_script("arguments[0].click();", btn_div)
    except Exception as e:
        print(e)

    element1 = browser.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/div[3]/div[1]/div/ul/li[5]/span')
    browser.execute_script("arguments[0].click();", element1)


if __name__ == '__main__':
    global global_user_name
    global global_passward
    global global_href
    global global_msg_receive_phone_number
    global binary_location
    global executable_path
    load_global_setting()
    # 对于启动参数，以启动参数为准
    if len(sys.argv) > 1:
        global_href = sys.argv[1]
    count = 0
    while True:
        try:
            browser = start_browser()

            # 登录
            browser_login(browser, global_user_name, global_passward)
            # 关闭弹出c窗口
            browser_close_popup(browser)

            loop_count = 0
            while True:
                loop_count += 1
                count += 1
                print('开始自动抢购脚本次数', loop_count)
                if count > 100:
                    count = 0
                    browser.quit()
                    break

                text = ''
                try:
                    js = 'window.location.href="{}";'.format(global_href)
                    browser.execute_script(js)
                    js = 'location.reload();'
                    browser.execute_script(js)
                    time.sleep(0.1)
                    text = WebDriverWait(browser, 5).until(
                        lambda browser: browser.find_element_by_class_name("red-color")).text
                    dtstr = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    print(f'{loop_count}[{dtstr}],{text}')
                except Exception as e:
                    print('刷新页面报错')
                try:
                    if '立即购买' in text:
                        WebDriverWait(browser, 10).until(
                            lambda browser: browser.find_element_by_xpath('//*[@id="footer_content"]/div[2]/a')).click()
                        # 点击进入抢货页面
                        btn_div = WebDriverWait(browser, 10).until(
                            lambda browser: browser.find_element_by_css_selector(
                                "[class='van-button van-button--danger van-button--large']"))
                        browser.execute_script("arguments[0].click();", btn_div)
                        print('点击进入抢货页面')
                        time.sleep(0.1)

                        # 点击进入购买页面
                        WebDriverWait(browser, 10).until(
                            lambda browser: browser.find_element_by_xpath('//*[@id="write_order"]/footer/div/div')).click()
                        time.sleep(0.1)
                        print('点击进入购买页面')

                        try:
                            # 点击进入支付页面,某些产品会跳出以旧换新活动
                            browser.find_element_by_xpath('//*[@id="app"]/div[1]/div[4]/div[2]/div[2]').click()
                            time.sleep(0.1)
                            print('点击进入支付页面')
                        except Exception as e:
                            print('没有以旧换新页面')

                        text1 = WebDriverWait(browser, 7).until(
                            lambda browser: browser.find_element_by_xpath('//*[@id="app"]/div[1]/button')).text
                        time.sleep(0.1)
                        print('点击进入支付页面')

                        if '支付' in text1:
                            print('抢到了')
                            SendMsg.sendMsg(global_msg_receive_phone_number, f'自动抢空调软件提醒：抢到了，请去代付款进行支付')
                            time.sleep(1)

                    else:
                        time.sleep(1)  # 如果没货，等1秒
                except Exception as e:
                    print(e)
        except Exception as e:
            traceback.print_exc()
            print(f'重启浏览器过程异常，等等待1分钟')
            time.sleep(60)
